﻿using System.IO;
using System.Net;
using System.Text;
using Cysharp.Threading.Tasks;

namespace Neatly.Module
{
    public class RequestModule : Singleton<RequestModule>
    {
        public async UniTask<(string, string)> Get(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Timeout = NeatlyConfig.REQUEST_TIMEOUT;
            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var responseStream = response.GetResponseStream();
                var reader = new StreamReader(responseStream);
                return (null, await reader.ReadToEndAsync());
            }
            return(response.StatusCode.ToString(), null);
        }

        public async UniTask<(string, string)> PostJson(string url, string param)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Timeout = NeatlyConfig.REQUEST_TIMEOUT;
            if (!string.IsNullOrEmpty(param))
            {
                var bytes = Encoding.UTF8.GetBytes(param);
                request.ContentLength = bytes.Length;
                var stream = await request.GetRequestStreamAsync();
                await stream.WriteAsync(bytes, 0, bytes.Length);
            }
            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var responseStream = response.GetResponseStream();
                var reader = new StreamReader(responseStream);
                return (null, await reader.ReadToEndAsync());
            }
            return(response.StatusCode.ToString(), null);
        }
    }
}